<template>
  <ContentWrap :style="`height: ${contentHeight}px;`">
    <div class="mb-10px routeHeader">
      <el-button
        @click="submitForm(1)"
        type="primary"
        :disabled="formLoading"
        v-if="['update', 'create'].includes(formType)"
        v-hasPermi="['order:marketing-shipping-note:save']"
        >保存</el-button
      >
      <el-button
        @click="submitForm(2)"
        type="primary"
        :disabled="formLoading"
        v-if="['update', 'create'].includes(formType)"
        v-hasPermi="['order:marketing-shipping-note:handle']"
        >提交</el-button
      >
      <el-button @click="goBack">关闭</el-button>
    </div>
    <div class="mb-10px">
      <el-button
        @click="createRow"
        type="primary"
        :disabled="formLoading"
        v-if="formType === 'create'"
        >新增行</el-button
      >
    </div>
    <el-scrollbar :max-height="`${contentHeight - 73}px`">
      <el-table border v-loading="formLoading" ref="multipleTableRef" :data="formData">
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column v-for="item, index in TableTitleList" :key="index" :label="item.label"
          :header-align="item.headerAlign" :align="item.align" :prop="item.field" min-width="200px">
          <template #default="scope">
            <template v-if="['productNumber'].includes(item.field)">
              <div class="d-flex">
                <el-select 
                  v-model="scope.row[item.field]"
                  filterable
                  remote 
                  placeholder="请选择产品编号"
                  :remote-method="getProductNumber"
                  @change="changeProductNumber(scope.$index, scope.row.productNumber)"
                  :loading="productNumberLoading"
                >
                  <el-option
                    v-for="item, index in productNumberList"
                    :key="index"
                    :label="item['productNumber']"
                    :value="item['productNumber']"
                  />
                </el-select>
                <el-button link class="ml-10px" @click="showProduct(scope.row, scope.$index)">
                  <el-icon :size="20">
                    <Search />
                  </el-icon>
                </el-button>
              </div>
            </template>
            <template v-else>
              <!-- 字典翻译 -->
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <div v-else>{{ scope.row[item.field] }}</div>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </ContentWrap>
  <!-- 产品列表 -->
  <product ref="productRef" @setProduct="setProduct" :contentHeight="contentHeight" />
</template>
<script setup lang="ts">
import * as MarketingShippingNoteApi from '@/api/orderManagement/marketingManagement/marketingShippingNote'
import * as ComponentApi from '@/api/componentApi/index'
import product from './product.vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { Search } from '@element-plus/icons-vue'

const message = useMessage() // 消息弹窗

interface DataType {
  orderNumber: string,
  customerName: string,
  dictOrderType: number,
  productNumber: string,
  productName: string,
  orderQuantity: number,
  dictStatus: number
}
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<DataType[]>([])

const TableTitleList = [
  {
    label: '订单号',
    field: 'orderNumber',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '客户名称',
    field: 'customerName',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '订单类型',
    field: 'dictOrderType',
    headerAlign: 'left',
    align: 'left',
    dictType: 'market_order_type'
  },
  {
    label: '产品编号',
    field: 'productNumber',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '产品名称',
    field: 'productName',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '订单数量',
    field: 'orderQuantity',
    headerAlign: 'left',
    align: 'left'
  },
  {
    label: '状态',
    field: 'dictStatus',
    headerAlign: 'left',
    align: 'left',
    dictType: 'order_marketing_shipping_note_status'
  }
]

const productNumberLoading = ref(false)
const productNumberList = ref([])
const contentHeight = ref(0)
const query = useRoute().query as any
const productRef = ref()

// 关闭
const tagsViewStore = useTagsViewStore()
const { currentRoute, push } = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(currentRoute.value)
  push('/orderManagement/orderManagement/marketing/marketingShippingNote')
}

/** 打开弹窗 */
const getData = async (type: string, id?: number) => {
  formType.value = type
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await MarketingShippingNoteApi.getMarketingShippingNote(id)
      formData.value = [data]
    } finally {
      formLoading.value = false
    }
  }
}

// 新增行
const createRow = () => {
  formData.value.push({
    orderNumber: '',
    customerName: '',
    dictOrderType: 0,
    productNumber: '',
    productName: '',
    orderQuantity: null,
    dictStatus: 0
  })
}

// 获取订单号
const getProductNumber = async (val: string) => {
  if (val) {
    productNumberLoading.value = true
    try {
      const data = await ComponentApi.getMarketingShippingNoteProduct({ orderNumber: '', productNumber: val })
      productNumberList.value = data
    } finally {
      productNumberLoading.value = false
    }
  } else {
    productNumberList.value = []
  }
}

// 选择产品编号
const changeProductNumber = async (index: number, productNumber: string) => {
  const data = await ComponentApi.getMarketingShippingNoteProduct({ orderNumber: '', productNumber: productNumber })
  formData.value[index] = data[0]
}

// 打开产品列表弹窗
const showProduct = (arr, index) => {
  productRef.value.open(arr, index)
}

// 设置产品明细
const setProduct = (val, index) => {
  formData.value[index] = val[0]
}

/** 提交表单 */
const submitForm = async (type: number) => {
  // 校验表单
  for (let i = 0; i < formData.value.length; i++) {
    if (!formData.value[i].orderNumber) {
      message.notifyError('订单号不能为空')
      return
    }
    if (!formData.value[i].productNumber) {
      message.notifyError('产品编号不能为空')
      return
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      type,
      data: formData.value
    } as unknown as MarketingShippingNoteApi.MarketingShippingNoteVO
    await MarketingShippingNoteApi.saveAndHandleMarketingShippingNote(data)
    message.success('操作成功')
    goBack()
  } finally {
    formLoading.value = false
  }
}

// 初始化
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 125
  getData(query.type, query.id)
})
</script>
<style lang="scss" scoped>
.d-flex {
  display: flex;
  align-items: center;
}
</style>
